import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 姚东名
 * Date: 2024-10-05
 * Time: 10:19
 */
public class HashBuck {
    static class Node {
        //有key值、value值、存储下一个位置的next
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }
    //有一个数组存储链表的头节点
    public Node[] array = new Node[10];
    //数组中有效的个数
    public int usedSize;
    //默认的负载因子
    public static final double DEFAULT_LOAD_FACTOR = 0.75f;

    //插入数据
    public void push(int key,int val) {
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                cur.val = val;//就是标志一下
                return;
            }
            cur = cur.next;
        }
        //走到这，没有找到当前链表中有这个key的节点，进行头插
        Node node = new Node(key, val);
        node.next = array[index];
        array[index] = node;
        usedSize++;
        //从这开始判断负载因子是否超过初始值，超过则需要扩容
        if(doLoadFactor() > DEFAULT_LOAD_FACTOR) {
            resize();
        }
    }
    private void resize() {
        //不能直接扩容
        //array = Arrays.copyOf(array, 2 * array.length);
        Node[] newArray = new Node[2 * array.length];
        for (int i = 0; i < array.length; i++) {//这一步就是把array数组的元素放到newArray数组中
            Node cur = array[i];
            while(cur != null) {
                int newIndex = cur.key % newArray.length;
                Node curN = cur.next;
                //同样是进行头插
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = curN;
            }
        }
        array = newArray;
    }
    private double doLoadFactor() {
        return this.usedSize * 1.0 / array.length;
    }
    //获得value的值
    public int getVal(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
